package adv8;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XMLADD {

	public static void main(String[] args) throws Exception {
		// 新增student子节点
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("students2.xml"));
		Element root = doc.getRootElement();

		Element newStu = root.addElement("student");
		newStu.addAttribute("kgcno", "399392");
		newStu.addAttribute("sex", "妖");
		newStu.addElement("name").setText("牛魔王");
		newStu.addElement("qq").setText("19328954");
		newStu.addElement("telephone").setText("13888888888");
		newStu.addElement("addr").setText("花果山北no-1");
		newStu.addElement("school").setText("花果山专修学院");
		// 写回Xml，先设置格式，防止在一行不可读
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter xm = new XMLWriter(new FileWriter("students2.xml"), format);
		xm.write(doc);
		xm.close();// 关闭
	}

}
